﻿HmJS.$Import('core.core');
//HmJS.$Import('core.element.base');

/*
---
version: 1.5-0
description: ScrollSpy is a small but powerful MooTools plugin that allows you to listen to scrolling within any DOM element and execute functions based upon the element's scroll position.
license: MIT-style license
download: http://mootools.net/forge/p/scrollspy
source: http://github.com/darkwing/ScrollSpy/

authors:
- David Walsh (http://davidwalsh.name)

requires:
core/1.2.1:   '*'

provides:
- ScrollSpy
...
*/

HmJS.register('util.dom.ScrollSpy', function ($ns) {

	var ScrollSpy = new Class({

		/* implements */
		Implements: [Options, Events],

		/* options */
		options: {
			container: window,
			max: 0,
			min: 0,
			mode: 'vertical'/*,
		onEnter: $empty,
		onLeave: $empty,
		onScroll: $empty,
		onTick: $empty
		*/
		},

		/* initialization */
		initialize: function (options) {
			/* set options */
			this.setOptions(options);
			this.container = document.id(this.options.container);
			this.enters = this.leaves = 0;
			this.inside = false;

			/* listener */
			var self = this;
			this.listener = function (e) {
				/* if it has reached the level */
				var position = self.container.getScroll(),
				xy = position[self.options.mode == 'vertical' ? 'y' : 'x'];
				/* if we reach the minimum and are still below the max... */
				if (xy >= self.options.min && (self.options.max == 0 || xy <= self.options.max)) {
					/* trigger enter event if necessary */
					if (!self.inside) {
						/* record as inside */
						self.inside = true;
						self.enters++;
						/* fire enter event */
						self.fireEvent('enter', [position, self.enters, e]);
					}
					/* trigger the "tick", always */
					self.fireEvent('tick', [position, self.inside, self.enters, self.leaves, e]);
				}
				/* trigger leave */
				else if (self.inside) {
					self.inside = false;
					self.leaves++;
					self.fireEvent('leave', [position, self.leaves, e]);
				}
				/* fire scroll event */
				self.fireEvent('scroll', [position, self.inside, self.enters, self.leaves, e]);
			};

			/* make it happen */
			this.addListener();
		},

		/* starts the listener */
		start: function () {
			this.container.addEvent('scroll', this.listener);
		},

		/* stops the listener */
		stop: function () {
			this.container.removeEvent('scroll', this.listener);
		},

		/* legacy */
		addListener: function () {
			this.start();
		}

	});

	return ScrollSpy;
});